package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.item.bo.SpuBO;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.SpecParam;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.search.client.CategoryClient;
import com.leyou.search.client.GoodsClient;
import com.leyou.search.client.SpecificationClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: taft
 * @Date: 2018-10-16 16:30
 */

@Service
public class IndexService {

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specificationClient;


    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsRepository goodsRepository;


    public Goods buildGoods(SpuBO spuBO) {
        /**
         * 1,数据的查询
         * 2，进行数据的封装
         * 3，数据的保存
         */
        
        

       
            Goods goods = new Goods();

            goods.setId(spuBO.getId());

            goods.setCid1(spuBO.getCid1());
            goods.setCid2(spuBO.getCid2());
            goods.setCid3(spuBO.getCid3());

            goods.setCreateTime(spuBO.getCreateTime());

            goods.setBrandId(spuBO.getBrandId());

            goods.setSubTitle(spuBO.getSubTitle());

            //以下要的数据没有直接数据，要封装


            //规格参数的查询根据分类以及可以搜索来查询
            List<SpecParam> specParams = specificationClient.querySpecParam(null, spuBO.getCid3(), true, null);

            //根据spuId查询spu的详情信息

            SpuDetail spuDetail = goodsClient.querySpuDetailById(spuBO.getId());

            //获取所有的通用的规格参数
            Map<Long, String> genericMap = JsonUtils.parseMap(spuDetail.getGenericSpec(), Long.class, String.class);

            //获取所有的特有的规格参数
            //特有规格参数的值
            Map<Long,List<String>> specialMap = JsonUtils.nativeRead(spuDetail.getSpecialSpec(),
                    new TypeReference<Map<Long, List<String>>>() {
                    });


            //处理规格参数显示问题，默认显示id+值，处理后显示id对应的名称+值
            Map<String, Object> specs = new HashMap<>();

            for (SpecParam param : specParams) {
                //规格参数的id
                Long paramId = param.getId();
                //规格参数的名字，例如CPU品牌，电池容量
                String name = param.getName();

                //通用参数
                Object value = null;
                if (param.getGeneric()) {
                    //通用参数
                    value = genericMap.get(paramId);

                    if (param.getNumeric()) {
                        //数值类型需要加分段

                        if (null==value){
                            value="";
                        }
                        value = this.chooseSegment(value.toString(), param);
                    }
                } else {//特有参数
                    value = specialMap.get(paramId);
                }
                if (null == value) {
                    value = "其他";
                }
                specs.put(name, value);
            }


            //可以搜索的字段（参数）
            goods.setSpecs(specs);


            List<Sku> skus = this.goodsClient.querySkuBySpuId(spuBO.getId());

            //当前spu对应的所有的sku并且是个json
            goods.setSkus(JsonUtils.serialize(skus));


            List<Long> priceList = new ArrayList<>();
            for (Sku sku : skus) {

                priceList.add(sku.getPrice());
            }


            //当前spu对应的所有sku的price集合
            goods.setPrice(priceList);


            //商品分类名称
            List<String> names = this.categoryClient.queryNameByIds(Arrays.asList(spuBO.getCid1(),spuBO.getCid2(),spuBO.getCid3()));
            String all = spuBO.getTitle()+" "+ StringUtils.join(names," ");
            //拼接字段
            goods.setAll(all);


         return goods;
        
    }

    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if(segs.length == 2){
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if(val >= begin && val < end){
                if(segs.length == 1){
                    result = segs[0] + p.getUnit() + "以上";
                }else if(begin == 0){
                    result = segs[1] + p.getUnit() + "以下";
                }else{
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }



    public void createIndex(Long id) {
        Spu spu = this.goodsClient.querySpuById(id);
        SpuBO spuBO = new SpuBO();
        BeanUtils.copyProperties(spu,spuBO);
        Goods goods = buildGoods(spuBO);
        //把goods对象保存到索引库
        this.goodsRepository.save(goods);
    }

    public void deleteIndex(Long id) {

    }
}
